import React, { useMemo, useState, useEffect, forwardRef, useImperativeHandle } from "react"
import { Spin, Button, Space, ImgDefault, Icon, message, Form, Input, Tag } from '@bytedance/mona-ui';
import DetailContent from "./detailContentBox"
import ZhutuList from "./zhutuList"
import { getSearchWordApi } from "@Api/toolsApi"
import { generatedAiInit } from "./generatedAiImages"
import './protStyle.scss'

function getStrLen(str) {
    var charsToReplace = ["～", '！', '¥', '（', '）', '【', '】', '「', '」', '，', '。'];

    // 将数组元素用管道符(|)连接，创建一个正则表达式
    var regex = new RegExp(charsToReplace.join('|'), 'g');

    return str.replace(regex, 'a').replace(/[^\x00-\xff]/g, "aa").length
}
function EditDeteail(props: any) {
    const { item, onChange, onChangeLodinStatus } = props
    const [searchWord, setSearchWord] = useState<any[]>([])
    const [searchWordMsg, setSearchWordMsg] = useState("")
    const [shearWorders, setShearWorders] = useState<any>(null)
    // const prettify_info: any[] = []

    const [deleailReFodata, setDeleailReFodata] = useState<any>(null)
    let [prettify_info, setPrettify_info] = useState<any[]>([])
    const [picimageList, setPicimageList] = useState<any[]>([])
    const [getAiImageLodinStatus, setGetAiImageLodinStatus] = useState(false)
    const [aiImageList, setAiImageList] = useState([])
    const [aiNewObject, setNewObject] = useState(null)

    useMemo(() => {
        if (item) {
            setDeleailReFodata(item)
            let deteilsData = item.description
            prettify_info = []
            deteilsData.split('src="').forEach((res, index) => {
                // console.log('ee', res.split("\" style=\""))
                const spliteUrls = res.split('" style="')
                spliteUrls.forEach((urls) => {
                    if (urls.includes("https") || urls.includes("http")) {
                        prettify_info.push({
                            url: urls,
                            id: index,
                            isNewImage: false,
                            islodin: false,
                            upStatus: true
                        })
                    }
                })
            })
            setPrettify_info(prettify_info)


            setPicimageList((() => {
                // console.log('这里调用生成AI图片', item.pic[0])
                // setGetAiImageLodinStatus(true)
                generatedAiInit({
                    product_id: item.product_id,
                    url: item.pic[0],
                    cb: (data) => {
                        // console.log('AI结果', data)
                        setNewObject(data)
                        setAiImageList(data.run_end_images)
                        onChangeLodinStatus(data)
                        // setGetAiImageLodinStatus(false)
                    },
                    setGetAiImageLodinStatus: setGetAiImageLodinStatus
                })
                return item.pic.map((urls, index) => {
                    return {
                        url: urls,
                        id: index + 1,
                        isNewImage: false,
                        islodin: false,
                        upStatus: true
                    }
                })
            })())
            getDeteAiCi()
        }
    }, [item])

    // let wroders: any = []
    let isAddList: number[] = []
    let addContent: string[] = []
    async function getDeteAiCi() {
        // 热搜词
        const gettiye = await Promise.all([
            getSearchWordApi({
                product_id: item.product_id
            }),
            getSearchWordApi({
                product_id: item.product_id,
                intention: "5",
                pageSize: 50
            })
        ])
        // console.log('gettiye', gettiye)
        let ghser: any = {}
        gettiye.forEach((res) => {
            // if (res.code === 10000) {
            if (!res.data) {
                return
            }
            if (ghser.data && ghser.data.length) {
                ghser.data = [...ghser.data, ...res.data]
            } else {
                ghser = res
            }
        })

        if (ghser.data && ghser.data.length) {
            setSearchWord(ghser.data)

        } else {
            setSearchWordMsg(ghser.msg)
        }

    }
    useEffect(() => {
        if (searchWord && searchWord.length) {
            setShearWorders(getTitleRefoter())
        }
    }, [searchWord])
    useEffect(() => {
        onChange && onChange({
            deleailReFodata,
            picimageList,
            prettify_info
        })
    }, [deleailReFodata, picimageList, prettify_info])
    if (!deleailReFodata) return

    function getTitleRefoter() {
        if (!searchWord || searchWord.length < 20) {
            return []
        }
        // return []

        const miyer: number = Math.floor(Math.random() * searchWord.length)
        if (!isAddList.includes(miyer)) {
            const strs = searchWord[miyer].cell_info?.query.query_value.value.value_str
            let interCount = strs.replace(/[^\x00-\xff]/g, "aa").length
            let interlength = addContent.join('').replace(/[^\x00-\xff]/g, "aa").length
            let outInterlength = 100 - interlength
            if (outInterlength >= interCount) {
                addContent.push(searchWord[miyer].cell_info.query.query_value.value.value_str)
                isAddList.push(miyer)
                getTitleRefoter()
            }
        } else {
            getTitleRefoter()
        }
        return addContent
    }
    return <Form size="small" layout="vertical">
        <Form.Item
            label="标题"
        >
            <Space direction="vertical" size={2} style={{
                width: '100%'
            }}>
                <Input value={deleailReFodata.name} onChange={(e) => {
                    setDeleailReFodata({
                        ...deleailReFodata,
                        name: e.target.value
                    })
                }} limit={60}
                    calcLength={(str) => {
                        return getStrLen(str)
                    }}
                ></Input>
                {!!(shearWorders && shearWorders.length) && <div>
                    <Space>

                        <Button type="link" icon={<Icon type="RefreshIcon" />} onClick={(e) => {
                            // console.log('eee添加')
                            isAddList = []
                            addContent = []
                            const refodater = getTitleRefoter()
                            setShearWorders(JSON.parse(JSON.stringify(refodater)))
                        }}>刷新</Button>
                        <Tag color="#000" type="success">
                            热搜词
                        </Tag>
                    </Space>

                    {shearWorders?.map((titel, keys) => {
                        return <Tag bordered type="default" key={keys} style={{
                            cursor: 'pointer',
                            // textWrap: 'nowrap'
                        }}
                        >
                            <span onClick={() => {
                                setDeleailReFodata({
                                    ...deleailReFodata,
                                    name: deleailReFodata.name + titel
                                })
                                // setIfromContent({
                                //     ...ifromContent,
                                //     TextValue: ifromContent.TextValue + titel
                                // })
                            }}>
                                {titel}
                            </span>

                        </Tag>
                    })}
                </div>}
            </Space>
        </Form.Item>
        <Form.Item
            label="主图"
        >
            <ZhutuList
                aiImageList={aiImageList}
                data={picimageList}
                getAiImageLodinStatus={getAiImageLodinStatus}
                aiNewObject={aiNewObject}
                onChange={(e) => {
                    setPicimageList([...e])
                }}
            ></ZhutuList>
            {/* <Spin spinning={getAiImageLodinStatus}>
               
            </Spin> */}
        </Form.Item>
        <Form.Item
            label="详情图"
        >
            <DetailContent
                searchWord={searchWord}
                aiNewObject={aiNewObject}
                getAiImageLodinStatus={getAiImageLodinStatus}
                picImages={{
                    list: prettify_info
                }}
                onChange={(e) => {
                    setPrettify_info([...e.list])
                }}
            />
        </Form.Item>
        {/* <Form.Item
            label="SUK"
        >
            SKU
        </Form.Item> */}
    </Form>
}


function EditItemBox(props: any) {
    const { item, reLoadDeteail, onChange, onChangeLodinStatus } = props
    if (!item) return null
    const [itemDataCopyState, setItemDataCopyState] = useState<any>({})
    const { record, detail } = item


    let upInfoData = {}



    useMemo(() => {
        setItemDataCopyState(item)
    }, [item])
    function copyToClipboard(text) {
        navigator.clipboard
            .writeText(text)
            .then(function () {
                message.success("复制成功")
            })
            .catch(function (err) {
                message.error("复制失败")
            })
    }
    return <div className="lterconter">
        <Space direction="vertical" style={{
            width: '100%',
        }}>
            <Space align="start">
                <ImgDefault src={record.base_item_info?.pic_url} alt="" style={{ width: '50px', height: '50px' }} />
                <Space direction="vertical" size={1}>
                    <div className="name" style={{
                        width: 1000,
                    }}>
                        {record.base_item_info?.item_name}
                    </div>
                    <div className="idcone" style={{
                        color: "#85878a"
                    }}>
                        <span className="id">ID：{record.base_item_info?.item_id}</span>
                        <Icon type="CopyIcon" className="copyiconitem"
                            style={{
                                marginLeft: 5,
                                cursor: "pointer"
                            }}
                            onClick={() => copyToClipboard(record.base_item_info?.item_id)}> </Icon>
                    </div>
                </Space>
            </Space>

            <Spin spinning={itemDataCopyState.lodinStatus}>

                {!itemDataCopyState.errStatus ?
                    <div className="scerssDom">
                        <EditDeteail item={detail} onChangeLodinStatus={onChangeLodinStatus} onChange={(e) => {
                            upInfoData = e
                            onChange && onChange(upInfoData)
                        }} />
                        {/* <Button onClick={() => {
                            console.log('收集好的当个数据， 可以使用', upInfoData)
                        }}>测试收集的数据</Button> */}
                    </div>
                    :
                    <Space className="errDom" align="center">
                        <span>商品加载错误</span>  <Button type="link" onClick={() => { reLoadDeteail(itemDataCopyState) }}>重新加载</Button>
                    </Space>}
            </Spin>
        </Space>

    </div>
}

export default EditItemBox